package com.ys.controller.api.purchase;

import com.ys.config.MenuId;
import com.ys.entity.finance.TcwWanliPaymentReturn;
import com.ys.entity.purchase.TcgPurchasePreStorage;
import com.ys.entity.sys.YsCol;
import com.ys.service.purchase.TcgPurchasePreStorageService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 采购预入库
 */
@Controller
@RequestMapping("/api/inter/tcgPurchasePreStorage")
public class ApiInterTcgPurchasePreStorageController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcgPurchasePreStorageController.class);


    @Autowired
    private TcgPurchasePreStorageService tcgPurchasePreStorageService;

    //菜单id
    private Long menuId = MenuId.TCG_PurchasePreStorage;

    @Autowired
    private CommonApiService<TcgPurchasePreStorage> commonApiService;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcgPurchasePreStorage:view";
    private final String PERMISSIONS_ADD = "tcgPurchasePreStorage:add";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @param cond
     * @return
     */
    public TcgPurchasePreStorage setSeachSql(TcgPurchasePreStorage cond){
        cond.addLeftJoin("YS_ProcInst Ysp ON Ysp.bid = A.bid")//流程表
                .addField("FORMAT(Ysp.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS updateTime1")//审核时间
            .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
                .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")
            .addLeftJoin("TCG_PurchaseContract pc on pc.bid = A.PurchaseContractBid")//采购合同单
            .addLeftJoin("TCW_PartnerBankInfo C on C.id = pc.PartnerBankInfoId")//供应方公司
                .addField("C.PartnerName partnerBankInfoName")
            .addLeftJoin("TCG_PurchasePreStorageSon ppss on ppss.pbid = A.bid")//采购预入库明细
                .addField("ppss.preStorageNum preStorageNum")
            .addLeftJoin("TCG_PurchaseContractItem tpc on tpc.id = ppss.PurchaseContractItemId")//采购合同管理（采购合同单明细）
                .addField("tpc.Pbid purchaseContractBid,tpc.SubPurchasePrice subPurchasePrice,tpc.id purchaseContractItemId,tpc.subBomNumber subBomNumber")
            .addLeftJoin("TCG_PurchaseAppointOrderProductComponent paoc on paoc.id = tpc.OrderProductComponentId")//预约采购子件明细
                .addField("paoc.SubCode subCode,paoc.subName subName,paoc.subCodeMerge subCodeMerge")
            .addLeftJoin("TCG_PurchaseAppointOrderItem paoi on paoi.id = paoc.pid")//预约采购商品明细
                .addField("paoi.Pbid appointOrderBid,paoi.ProductCode productCode,paoi.ProductName productName,paoi.CodeMerge codeMerge")
            .addLeftJoin("TCG_PurchaseAppointOrder pao on pao.Bid = paoi.Pbid")//预约采购单
            .addLeftJoin("THR_OperateCompanyApply TOCA ON TOCA.Vgsbm = pao.Vgsbm")
                .addField("pao.Vgsbm vgsbm,TOCA.Vgsjc AS vgsjc")//运营公司简称
            .addLeftJoin("TB_CompanyInfo D ON D.Vid = pc.CompanyInfoVid")//购买方公司
                .addField("D.Vname companyName")
        ;
        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }

    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcgPurchasePreStorage cond, String conditions
    ){
        try {
            cond = setSeachSql(cond);
            String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");
            if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
                cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcgPurchasePreStorageService.add(params,menuId);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcgPurchasePreStorageService.update(params,menuId);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tcgPurchasePreStorageService.del(id);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 流转通过
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            TcgPurchasePreStorage entity = new TcgPurchasePreStorage().setId(id).queryFirst();
            return tcgPurchasePreStorageService.flowPass(entity.getBid(), ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        TcgPurchasePreStorage entity = new TcgPurchasePreStorage().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return tcgPurchasePreStorageService.flowRefuse(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            TcgPurchasePreStorage entity = new TcgPurchasePreStorage().setId(id).queryFirst();
            String bid = entity.getBid();
            return tcgPurchasePreStorageService.flowInit(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgPurchasePreStorage cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");
            if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
                cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
            }


            cond = commonApiService.dataAuth(menuId, cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TcgPurchasePreStorage> util = new ExportExcelUtils<>(new TcgPurchasePreStorage());
            String toFilePath = util.exportExcel(listData, listField, "采购预入库报表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }
}
